package com.luqili.utils.pub.number;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

public class HexTools {
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
        'E', 'F'};

    /**
     * 处理Hex,去除空格,自动截取(src的前len位,不足的补0),非16进制数替换为0,返回为大写状态
     *
     * @param src
     * @param len
     * @return
     */
    public static String handHex(String src, int len) {
        src = StrUtil.cleanBlank(src);
        if (src.length() > len) {
            src = StrUtil.sub(src, 0, len);
        } else if (src.length() < len) {
            src = StrUtil.padAfter(src, len, "0");
        }
        src = src.toUpperCase();
        StringBuilder sb = new StringBuilder();
        for (char c : src.toCharArray()) {
            if (Arrays.binarySearch(DIGITS_UPPER, c) >= 0) {
                sb.append(c);
            } else {
                sb.append('0');
            }
        }
        return sb.toString();
    }

    /**
     * 验证是否未16进制的字符
     *
     * @param src
     * @return
     */
    public static boolean isHexChar(String src) {
        if (StrUtil.isBlank(src)) {
            return false;
        }
        src = src.toUpperCase();
        for (char c : src.toCharArray()) {
            if (Arrays.binarySearch(DIGITS_UPPER, c) < 0) {
                return false;
            }
        }
        return true;
    }
}
